<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.1.2">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.1.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.1.2">


  <link rel="mask-icon" href="/images/logo.svg?v=7.1.2" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="NumPy(Numerical Python) 是 Python 语言的一个扩展程序库，支持大量的维度数组与矩阵运算，此外也针对数组运算提供大量的数学函数库。">
<meta name="keywords" content="Python,数据分析,AI进阶">
<meta property="og:type" content="article">
<meta property="og:title" content="Numpy">
<meta property="og:url" content="https://rencheng.cc/2018/11/30/datascience/Numpy/index.html">
<meta property="og:site_name" content="PHOENIX&#39;s Blog">
<meta property="og:description" content="NumPy(Numerical Python) 是 Python 语言的一个扩展程序库，支持大量的维度数组与矩阵运算，此外也针对数组运算提供大量的数学函数库。">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-11-30T13:58:11.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Numpy">
<meta name="twitter:description" content="NumPy(Numerical Python) 是 Python 语言的一个扩展程序库，支持大量的维度数组与矩阵运算，此外也针对数组运算提供大量的数学函数库。">



  <link rel="alternate" href="/atom.xml" title="PHOENIX's Blog" type="application/atom+xml">



  
  
  <link rel="canonical" href="https://rencheng.cc/2018/11/30/datascience/Numpy/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Numpy | PHOENIX's Blog</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">PHOENIX's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">Enjoy the journey of life</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://rencheng.cc/2018/11/30/datascience/Numpy/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="任成">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="PHOENIX's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Numpy

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-11-30 21:58:11" itemprop="dateCreated datePublished" datetime="2018-11-30T21:58:11+08:00">2018-11-30</time>
            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/教程/" itemprop="url" rel="index"><span itemprop="name">教程</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                <span title="本文字数">15k</span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>NumPy(Numerical Python) 是 Python 语言的一个扩展程序库，支持大量的维度数组与矩阵运算，此外也针对数组运算提供大量的数学函数库。<br><a id="more"></a></p>
<h2 id="numpy概述"><a href="#numpy概述" class="headerlink" title="numpy概述"></a>numpy概述</h2><ol>
<li>Numerical Python，数值的Python，补充了Python语言所欠缺的数值计算能力。</li>
<li>Numpy是其它数据分析及机器学习库的底层库。</li>
<li>Numpy完全标准C语言实现，运行效率充分优化。</li>
<li>Numpy开源免费。</li>
</ol>
<h3 id="numpy历史"><a href="#numpy历史" class="headerlink" title="numpy历史"></a>numpy历史</h3><ol>
<li>1995年，Numeric，Python语言数值计算扩充。</li>
<li>2001年，Scipy-&gt;Numarray，多维数组运算。</li>
<li>2005年，Numeric+Numarray-&gt;Numpy。</li>
<li>2006年，Numpy脱离Scipy成为独立的项目。</li>
</ol>
<h3 id="numpy的核心：多维数组"><a href="#numpy的核心：多维数组" class="headerlink" title="numpy的核心：多维数组"></a>numpy的核心：多维数组</h3><ol>
<li>代码简洁：减少Python代码中的循环。</li>
<li>底层实现：厚内核(C)+薄接口(Python)，保证性能。</li>
</ol>
<h2 id="numpy基础"><a href="#numpy基础" class="headerlink" title="numpy基础"></a>numpy基础</h2><h3 id="ndarray数组"><a href="#ndarray数组" class="headerlink" title="ndarray数组"></a>ndarray数组</h3><p>用np.ndarray类的对象表示n维数组</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">ary = np.array([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>])</span><br><span class="line">print(type(ary))</span><br></pre></td></tr></table></figure>
<h4 id="内存中的ndarray对象"><a href="#内存中的ndarray对象" class="headerlink" title="内存中的ndarray对象"></a>内存中的ndarray对象</h4><p><strong>元数据（metadata）</strong></p>
<p>存储对目标数组的描述信息，</p>
<div class="table-container">
<table>
<thead>
<tr>
<th>字段</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>dim</td>
<td>轴</td>
</tr>
<tr>
<td>count</td>
<td>长度</td>
</tr>
<tr>
<td>dimensions</td>
<td></td>
</tr>
<tr>
<td>dtype</td>
<td>类型</td>
</tr>
<tr>
<td>data</td>
<td>数据</td>
</tr>
<tr>
<td>…</td>
<td>…</td>
</tr>
</tbody>
</table>
</div>
<p><strong>实际数据</strong></p>
<p>完整的数组数据</p>
<blockquote>
<p>将实际数据与元数据分开存放，一方面提高了内存空间的使用效率，另一方面减少对实际数据的访问频率，提高性能。</p>
</blockquote>
<h4 id="ndarray数组对象的特点"><a href="#ndarray数组对象的特点" class="headerlink" title="ndarray数组对象的特点"></a>ndarray数组对象的特点</h4><ol>
<li>Numpy数组是<strong>同质数组</strong>，即所有元素的<strong>数据类型必须相同</strong></li>
<li>Numpy数组的下标从0开始，最后一个元素的下标为数组长度减1</li>
</ol>
<h4 id="ndarray数组对象的创建"><a href="#ndarray数组对象的创建" class="headerlink" title="ndarray数组对象的创建"></a>ndarray数组对象的创建</h4><p>np.array(任何可被解释为Numpy数组的逻辑结构)</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">a = np.array([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>])</span><br><span class="line">print(a)</span><br></pre></td></tr></table></figure>
<p>np.arange(起始值(0),终止值,步长(1))</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="comment"># arange 生成一个等差数列</span></span><br><span class="line">a = np.arange(<span class="number">0</span>, <span class="number">5</span>, <span class="number">1</span>)</span><br><span class="line">print(a)</span><br><span class="line">b = np.arange(<span class="number">0</span>, <span class="number">10</span>, <span class="number">2</span>)</span><br><span class="line">print(b)</span><br></pre></td></tr></table></figure>
<p>np.zeros(数组元素个数, dtype=’类型’)</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">a = np.zeros(<span class="number">10</span>)</span><br><span class="line">print(a)</span><br></pre></td></tr></table></figure>
<p>np.ones(数组元素个数, dtype=’类型’)</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">a = np.ones(<span class="number">10</span>)</span><br><span class="line">print(a)</span><br></pre></td></tr></table></figure>
<h4 id="ndarray对象属性的基本操作"><a href="#ndarray对象属性的基本操作" class="headerlink" title="ndarray对象属性的基本操作"></a>ndarray对象属性的基本操作</h4><p><strong>数组的维度：</strong>np.ndarray.shape</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">ary = np.array([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>])</span><br><span class="line">print(type(ary), ary, ary.shape)</span><br><span class="line"><span class="comment">#二维数组</span></span><br><span class="line">ary = np.array([</span><br><span class="line">    [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>],</span><br><span class="line">    [<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>]</span><br><span class="line">])</span><br><span class="line">print(type(ary), ary, ary.shape)</span><br></pre></td></tr></table></figure>
<p><strong>元素的类型：</strong>np.ndarray.dtype</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># test ndarray.dtype</span></span><br><span class="line">ary = np.array([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>])</span><br><span class="line">print(ary, ary.dtype)</span><br><span class="line"><span class="comment"># ary.dtype = 'int64'    error</span></span><br><span class="line"><span class="comment"># print(ary, ary.dtype)</span></span><br><span class="line"><span class="comment"># 源数组类型不变</span></span><br><span class="line">ary = ary.astype(<span class="string">'float64'</span>) <span class="comment"># 返回新的对象</span></span><br><span class="line">print(ary, ary.dtype)</span><br><span class="line">ary = ary.astype(<span class="string">'str'</span>) <span class="comment"># 返回新的对象</span></span><br><span class="line">print(ary, ary.dtype)</span><br></pre></td></tr></table></figure>
<p><strong>数组元素的个数：</strong>np.ndarray.size </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">ary = np.array([</span><br><span class="line">    [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>],</span><br><span class="line">    [<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>]</span><br><span class="line">])</span><br><span class="line"><span class="comment">#观察维度，size，len的区别</span></span><br><span class="line">print(ary.shape, ary.size, len(ary))</span><br></pre></td></tr></table></figure>
<p><strong>数组元素索引(下标)</strong></p>
<p>数组对象[…, 页号, 行号, 列号]</p>
<p>下标从0开始，到数组len-1结束。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">a = np.array([[[<span class="number">1</span>, <span class="number">2</span>],</span><br><span class="line">               [<span class="number">3</span>, <span class="number">4</span>]],</span><br><span class="line">              [[<span class="number">5</span>, <span class="number">6</span>],</span><br><span class="line">               [<span class="number">7</span>, <span class="number">8</span>]]])</span><br><span class="line">print(a, a.shape)</span><br><span class="line">print(a[<span class="number">0</span>])</span><br><span class="line">print(a[<span class="number">0</span>][<span class="number">0</span>])</span><br><span class="line">print(a[<span class="number">0</span>][<span class="number">0</span>][<span class="number">0</span>])</span><br><span class="line">print(a[<span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>])</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(a.shape[<span class="number">0</span>]):</span><br><span class="line">    <span class="keyword">for</span> j <span class="keyword">in</span> range(a.shape[<span class="number">1</span>]):</span><br><span class="line">        <span class="keyword">for</span> k <span class="keyword">in</span> range(a.shape[<span class="number">2</span>]):</span><br><span class="line">            print(a[i, j, k])</span><br></pre></td></tr></table></figure>
<h4 id="ndarray对象属性操作详解"><a href="#ndarray对象属性操作详解" class="headerlink" title="ndarray对象属性操作详解"></a>ndarray对象属性操作详解</h4><p><strong>Numpy的内部基本数据类型</strong></p>
<div class="table-container">
<table>
<thead>
<tr>
<th>类型名</th>
<th>类型表示符</th>
</tr>
</thead>
<tbody>
<tr>
<td>布尔型</td>
<td>bool_</td>
</tr>
<tr>
<td>有符号整数型</td>
<td>int8(-128~127)/int16/int32/int64</td>
</tr>
<tr>
<td>无符号整数型</td>
<td>uint8(0~255)/uint16/uint32/uint64</td>
</tr>
<tr>
<td>浮点型</td>
<td>float16/float32/float64</td>
</tr>
<tr>
<td>复数型</td>
<td>complex64/complex128        3</td>
</tr>
<tr>
<td>字串型</td>
<td>str_，每个字符用32位Unicode编码表示</td>
</tr>
</tbody>
</table>
</div>
<p><strong>自定义复合类型</strong><br>同时演示设置dtype的几种方式<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"></span><br><span class="line">data = [(<span class="string">'zs'</span>, [<span class="number">50</span>,<span class="number">51</span>,<span class="number">52</span>], <span class="number">15</span>),</span><br><span class="line">		(<span class="string">'ls'</span>, [<span class="number">83</span>,<span class="number">71</span>,<span class="number">62</span>], <span class="number">16</span>),</span><br><span class="line">		(<span class="string">'ww'</span>, [<span class="number">90</span>,<span class="number">91</span>,<span class="number">92</span>], <span class="number">17</span>)]</span><br><span class="line"></span><br><span class="line"><span class="comment">#第一种dtype的设置方式</span></span><br><span class="line">ary = np.array(data,dtype=<span class="string">'U2, 3int32, int32'</span>)</span><br><span class="line">print(ary, ary[<span class="number">0</span>][<span class="number">1</span>])</span><br><span class="line">print(ary[<span class="number">0</span>][<span class="string">'f0'</span>])</span><br><span class="line"></span><br><span class="line"><span class="comment">#第二种dtype的设置方式</span></span><br><span class="line">ary = np.array(data, </span><br><span class="line">		dtype=[ (<span class="string">'name'</span>, <span class="string">'str'</span>, <span class="number">2</span>), </span><br><span class="line">				(<span class="string">'scores'</span>, <span class="string">'int32'</span>, <span class="number">3</span>), </span><br><span class="line">				(<span class="string">'age'</span>, <span class="string">'int32'</span>, <span class="number">1</span>)])</span><br><span class="line">print(<span class="string">'-'</span> * <span class="number">45</span>)</span><br><span class="line">print(ary, ary.dtype)</span><br><span class="line">print(ary[<span class="number">0</span>][<span class="string">'age'</span>]) <span class="comment"># 返回zs的年龄</span></span><br><span class="line">print(ary[<span class="number">2</span>][<span class="string">'scores'</span>]) <span class="comment"># 返回ww的成绩</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 第三种dtype的设置方式</span></span><br><span class="line">ary = np.array(data, dtype=&#123;</span><br><span class="line">	<span class="string">'names'</span>:[<span class="string">'name'</span>, <span class="string">'scores'</span>, <span class="string">'age'</span>],</span><br><span class="line">	<span class="string">'formats'</span>:[<span class="string">'U2'</span>, <span class="string">'3int32'</span>, <span class="string">'int32'</span>]&#125;)</span><br><span class="line">print(ary)</span><br><span class="line">print(ary[<span class="number">0</span>][<span class="string">'age'</span>]) <span class="comment"># 返回zs的年龄</span></span><br><span class="line">print(ary[<span class="number">2</span>][<span class="string">'scores'</span>]) <span class="comment"># 返回ww的成绩</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 第四种dtype的设置方式</span></span><br><span class="line">d = np.array(data, dtype=&#123;<span class="string">'name'</span>: (<span class="string">'U3'</span>, <span class="number">0</span>),</span><br><span class="line">                    <span class="string">'scores'</span>: (<span class="string">'3int32'</span>, <span class="number">16</span>),</span><br><span class="line">                    <span class="string">'age'</span>: (<span class="string">'int32'</span>, <span class="number">28</span>)&#125;)</span><br><span class="line">print(d[<span class="number">0</span>][<span class="string">'name'</span>], d[<span class="number">0</span>][<span class="string">'scores'</span>], d.itemsize)</span><br><span class="line"></span><br><span class="line"><span class="comment"># ndarray数组存放日期数据</span></span><br><span class="line">dates = [<span class="string">'2011-01-01'</span>, <span class="string">'2012-01-01'</span>, </span><br><span class="line">		 <span class="string">'2011-02-01'</span>, <span class="string">'2012'</span>, </span><br><span class="line">		 <span class="string">'2011-01-01 10:10:10'</span>]</span><br><span class="line">ary = np.array(dates)</span><br><span class="line">print(ary, ary.dtype)</span><br><span class="line">ary = ary.astype(<span class="string">'M8[D]'</span>)</span><br><span class="line">print(ary, ary.dtype, ary[<span class="number">1</span>]-ary[<span class="number">0</span>])</span><br><span class="line"><span class="comment"># 输出31 days</span></span><br></pre></td></tr></table></figure></p>
<p><strong>类型字符码</strong></p>
<div class="table-container">
<table>
<thead>
<tr>
<th>类型</th>
<th>字符码</th>
</tr>
</thead>
<tbody>
<tr>
<td>np.bool_</td>
<td>?</td>
</tr>
<tr>
<td>np.int8/16/32/64</td>
<td>i1/i2/i4/i8</td>
</tr>
<tr>
<td>np.uint8/16/32/64</td>
<td>u1/u2/u4/u8</td>
</tr>
<tr>
<td>np.float/16/32/64</td>
<td>f2/f4/f8</td>
</tr>
<tr>
<td>np.complex64/128</td>
<td>c8/c16</td>
</tr>
<tr>
<td>np.str_</td>
<td>U&lt;字符数&gt;</td>
</tr>
<tr>
<td>np.datetime64</td>
<td>M8[Y] M8[M] M8[D] M8[h] M8[m] M8[s]</td>
</tr>
</tbody>
</table>
</div>
<p><strong>字节序前缀，用于多字节整数和字符串：</strong><br><code>&lt;/&gt;/[=]分别表示小端/大端/硬件字节序。</code></p>
<p><strong>类型字符码格式</strong></p>
<p>&lt;字节序前缀&gt;&lt;维度&gt;&lt;类型&gt;&lt;字节数或字符数&gt;</p>
<div class="table-container">
<table>
<thead>
<tr>
<th>3i4</th>
<th>释义</th>
</tr>
</thead>
<tbody>
<tr>
<td>3i4</td>
<td>3个元素的一维数组，每个元素都是整型，每个整型元素占4个字节。</td>
</tr>
<tr>
<td>&lt;(2,3)u8</td>
<td>小端字节序，6个元素2行3列的二维数组，每个元素都是无符号整型，每个无符号整型元素占8个字节。</td>
</tr>
<tr>
<td>U7</td>
<td>包含7个字符的Unicode字符串，每个字符占4个字节，采用默认字节序。</td>
</tr>
</tbody>
</table>
</div>
<h5 id="ndarray数组对象的维度操作"><a href="#ndarray数组对象的维度操作" class="headerlink" title="ndarray数组对象的维度操作"></a>ndarray数组对象的维度操作</h5><p><strong>视图变维（数据共享）：</strong> reshape() 与 ravel() </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">a = np.arange(<span class="number">1</span>, <span class="number">9</span>)</span><br><span class="line">print(a)		<span class="comment"># [1 2 3 4 5 6 7 8]</span></span><br><span class="line">b = a.reshape(<span class="number">2</span>, <span class="number">4</span>)	<span class="comment">#视图变维  : 变为2行4列的二维数组</span></span><br><span class="line">print(b)</span><br><span class="line">c = b.reshape(<span class="number">2</span>, <span class="number">2</span>, <span class="number">2</span>) <span class="comment">#视图变维    变为2页2行2列的三维数组</span></span><br><span class="line">print(c)</span><br><span class="line">d = c.ravel()	<span class="comment">#视图变维	变为1维数组</span></span><br><span class="line">print(d)</span><br></pre></td></tr></table></figure>
<p><strong>复制变维（数据独立）：</strong>flatten()</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">e = c.flatten()</span><br><span class="line">print(e)</span><br><span class="line">a += <span class="number">10</span></span><br><span class="line">print(a, e, sep=<span class="string">'\n'</span>)</span><br></pre></td></tr></table></figure>
<p><strong>就地变维：直接改变原数组对象的维度，不返回新数组</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">a.shape = (<span class="number">2</span>, <span class="number">4</span>)</span><br><span class="line">print(a)</span><br><span class="line">a.resize(<span class="number">2</span>, <span class="number">2</span>, <span class="number">2</span>)</span><br><span class="line">print(a)</span><br></pre></td></tr></table></figure>
<h5 id="ndarray数组切片操作"><a href="#ndarray数组切片操作" class="headerlink" title="ndarray数组切片操作"></a>ndarray数组切片操作</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#数组对象切片的参数设置与列表切面参数类似</span></span><br><span class="line"><span class="comment">#  步长+：默认切从首到尾</span></span><br><span class="line"><span class="comment">#  步长-：默认切从尾到首</span></span><br><span class="line">数组对象[起始位置:终止位置:步长]</span><br><span class="line"><span class="comment">#默认位置步长：1</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">a = np.arange(<span class="number">1</span>, <span class="number">10</span>)</span><br><span class="line">print(a)  <span class="comment"># 1 2 3 4 5 6 7 8 9</span></span><br><span class="line">print(a[:<span class="number">3</span>])  <span class="comment"># 1 2 3</span></span><br><span class="line">print(a[<span class="number">3</span>:<span class="number">6</span>])   <span class="comment"># 4 5 6</span></span><br><span class="line">print(a[<span class="number">6</span>:])  <span class="comment"># 7 8 9</span></span><br><span class="line">print(a[::<span class="number">-1</span>])  <span class="comment"># 9 8 7 6 5 4 3 2 1</span></span><br><span class="line">print(a[:<span class="number">-4</span>:<span class="number">-1</span>])  <span class="comment"># 9 8 7</span></span><br><span class="line">print(a[<span class="number">-4</span>:<span class="number">-7</span>:<span class="number">-1</span>])  <span class="comment"># 6 5 4</span></span><br><span class="line">print(a[<span class="number">-7</span>::<span class="number">-1</span>])  <span class="comment"># 3 2 1</span></span><br><span class="line">print(a[::])  <span class="comment"># 1 2 3 4 5 6 7 8 9</span></span><br><span class="line">print(a[:])  <span class="comment"># 1 2 3 4 5 6 7 8 9</span></span><br><span class="line">print(a[::<span class="number">3</span>])  <span class="comment"># 1 4 7</span></span><br><span class="line">print(a[<span class="number">1</span>::<span class="number">3</span>])  <span class="comment"># 2 5 8</span></span><br><span class="line">print(a[<span class="number">2</span>::<span class="number">3</span>])  <span class="comment"># 3 6 9</span></span><br></pre></td></tr></table></figure>
<p><strong>多维数组的切片操作</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 多维数组切片</span></span><br><span class="line">print(<span class="string">'-'</span> * <span class="number">45</span>)</span><br><span class="line">a = np.arange(<span class="number">1</span>, <span class="number">10</span>)</span><br><span class="line">a = a.reshape(<span class="number">3</span>, <span class="number">3</span>)</span><br><span class="line">print(a)</span><br><span class="line">print(a[:<span class="number">2</span>, :])  <span class="comment"># 切出前两行数据</span></span><br><span class="line">print(a[:<span class="number">2</span>, :<span class="number">2</span>])  <span class="comment"># 切出前两行两列数据</span></span><br><span class="line">print(a[::<span class="number">2</span>, :])  <span class="comment">#</span></span><br></pre></td></tr></table></figure>
<h5 id="ndarray数组的掩码操作"><a href="#ndarray数组的掩码操作" class="headerlink" title="ndarray数组的掩码操作"></a><strong>ndarray数组的掩码操作</strong></h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">a = np.array([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>])</span><br><span class="line">print(a + <span class="number">10</span>)</span><br><span class="line">print(a * <span class="number">2.5</span>)</span><br><span class="line">print(a + a)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 输出100以内3的倍数</span></span><br><span class="line">a = np.arange(<span class="number">1</span>, <span class="number">10</span>)</span><br><span class="line">mask = a % <span class="number">3</span> == <span class="number">0</span></span><br><span class="line">print(mask)</span><br><span class="line">print(a[mask])</span><br><span class="line"></span><br><span class="line">mask = [<span class="number">2</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">3</span>, <span class="number">6</span>, <span class="number">6</span>, <span class="number">4</span>, <span class="number">4</span>]</span><br><span class="line">print(a)</span><br><span class="line">print(a[mask])</span><br></pre></td></tr></table></figure>
<blockquote>
<p>常用语从大数组中获取子集的操作</p>
</blockquote>
<h5 id="多维数组的组合与拆分"><a href="#多维数组的组合与拆分" class="headerlink" title="多维数组的组合与拆分"></a>多维数组的组合与拆分</h5><p>垂直方向操作：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">a = np.arange(<span class="number">1</span>, <span class="number">7</span>).reshape(<span class="number">2</span>, <span class="number">3</span>)</span><br><span class="line">b = np.arange(<span class="number">7</span>, <span class="number">13</span>).reshape(<span class="number">2</span>, <span class="number">3</span>)</span><br><span class="line"><span class="comment"># 垂直方向完成组合操作，生成新数组</span></span><br><span class="line">c = np.vstack((a, b))</span><br><span class="line"><span class="comment"># 垂直方向完成拆分操作，生成两个数组</span></span><br><span class="line">d, e = np.vsplit(c, <span class="number">2</span>)</span><br></pre></td></tr></table></figure>
<p>水平方向操作：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">a = np.arange(<span class="number">1</span>, <span class="number">7</span>).reshape(<span class="number">2</span>, <span class="number">3</span>)</span><br><span class="line">b = np.arange(<span class="number">7</span>, <span class="number">13</span>).reshape(<span class="number">2</span>, <span class="number">3</span>)</span><br><span class="line"><span class="comment"># 水平方向完成组合操作，生成新数组 </span></span><br><span class="line">c = np.hstack((a, b))</span><br><span class="line"><span class="comment"># 水平方向完成拆分操作，生成两个数组</span></span><br><span class="line">d, e = np.hsplit(c, <span class="number">2</span>)</span><br></pre></td></tr></table></figure>
<p>深度方向操作：（3维）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">a = np.arange(<span class="number">1</span>, <span class="number">7</span>).reshape(<span class="number">2</span>, <span class="number">3</span>)</span><br><span class="line">b = np.arange(<span class="number">7</span>, <span class="number">13</span>).reshape(<span class="number">2</span>, <span class="number">3</span>)</span><br><span class="line"><span class="comment"># 深度方向（3维）完成组合操作，生成新数组</span></span><br><span class="line">i = np.dstack((a, b))</span><br><span class="line"><span class="comment"># 深度方向（3维）完成拆分操作，生成两个数组</span></span><br><span class="line">k, l = np.dsplit(i, <span class="number">2</span>)</span><br></pre></td></tr></table></figure>
<p>多维数组组合与拆分的相关函数：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 通过axis作为关键字参数指定组合的方向，取值如下：</span></span><br><span class="line"><span class="comment"># 若待组合的数组都是二维数组：</span></span><br><span class="line"><span class="comment">#	0: 垂直方向组合</span></span><br><span class="line"><span class="comment">#	1: 水平方向组合</span></span><br><span class="line"><span class="comment"># 若待组合的数组都是三维数组：</span></span><br><span class="line"><span class="comment">#	0: 垂直方向组合</span></span><br><span class="line"><span class="comment">#	1: 水平方向组合</span></span><br><span class="line"><span class="comment">#	2: 深度方向组合</span></span><br><span class="line">np.concatenate((a, b), axis=<span class="number">0</span>)</span><br><span class="line"><span class="comment"># 通过给出的数组与要拆分的份数，按照某个方向进行拆分，axis的取值同上</span></span><br><span class="line">np.split(c, <span class="number">2</span>, axis=<span class="number">0</span>)</span><br></pre></td></tr></table></figure>
<p>长度不等的数组组合：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">a = np.array([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>])</span><br><span class="line">b = np.array([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>])</span><br><span class="line"><span class="comment"># 填充b数组使其长度与a相同</span></span><br><span class="line"><span class="comment"># pad_width=(a, b)：在数组首部补a个元素，尾部补b个元素</span></span><br><span class="line">b = np.pad(b, pad_width=(<span class="number">0</span>, <span class="number">1</span>), mode=<span class="string">'constant'</span>, constant_values=<span class="number">-1</span>)</span><br><span class="line">print(b)</span><br><span class="line"><span class="comment"># 垂直方向完成组合操作，生成新数组</span></span><br><span class="line">c = np.vstack((a, b))</span><br><span class="line">print(c)</span><br></pre></td></tr></table></figure>
<p>简单的一维数组组合方案</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">a = np.arange(<span class="number">1</span>,<span class="number">9</span>)		<span class="comment">#[1, 2, 3, 4, 5, 6, 7, 8]</span></span><br><span class="line">b = np.arange(<span class="number">9</span>,<span class="number">17</span>)		<span class="comment">#[9,10,11,12,13,14,15,16]</span></span><br><span class="line"><span class="comment">#把两个数组摞在一起成两行</span></span><br><span class="line">c = np.row_stack((a, b))</span><br><span class="line">print(c)</span><br><span class="line"><span class="comment">#把两个数组组合在一起成两列</span></span><br><span class="line">d = np.column_stack((a, b))</span><br><span class="line">print(d)</span><br></pre></td></tr></table></figure>
<h4 id="ndarray类的其他属性"><a href="#ndarray类的其他属性" class="headerlink" title="ndarray类的其他属性"></a>ndarray类的其他属性</h4><ul>
<li>shape - 维度</li>
<li>dtype - 元素类型</li>
<li>size - 元素数量</li>
<li>ndim - 维数，len(shape)</li>
<li>itemsize - 元素字节数</li>
<li>nbytes - 总字节数 = size x itemsize</li>
<li>real - 复数数组的实部数组</li>
<li>imag - 复数数组的虚部数组</li>
<li>T - 数组对象的转置视图</li>
<li>flat - 扁平迭代器</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">a = np.array([[<span class="number">1</span> + <span class="number">1j</span>, <span class="number">2</span> + <span class="number">4j</span>, <span class="number">3</span> + <span class="number">7j</span>],</span><br><span class="line">              [<span class="number">4</span> + <span class="number">2j</span>, <span class="number">5</span> + <span class="number">5j</span>, <span class="number">6</span> + <span class="number">8j</span>],</span><br><span class="line">              [<span class="number">7</span> + <span class="number">3j</span>, <span class="number">8</span> + <span class="number">6j</span>, <span class="number">9</span> + <span class="number">9j</span>]])</span><br><span class="line">print(a.shape)</span><br><span class="line">print(a.dtype)</span><br><span class="line">print(a.ndim)</span><br><span class="line">print(a.size)</span><br><span class="line">print(a.itemsize)</span><br><span class="line">print(a.nbytes)</span><br><span class="line">print(a.real, a.imag, sep=<span class="string">'\n'</span>)</span><br><span class="line">print(a.T)</span><br><span class="line">print([elem <span class="keyword">for</span> elem <span class="keyword">in</span> a.flat])</span><br><span class="line">b = a.tolist()</span><br><span class="line">print(b)</span><br></pre></td></tr></table></figure>
<h3 id="相关函数"><a href="#相关函数" class="headerlink" title="相关函数"></a>相关函数</h3><h4 id="算数平均值"><a href="#算数平均值" class="headerlink" title="算数平均值"></a>算数平均值</h4><figure class="highlight armasm"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">S = [<span class="built_in">s1</span>, <span class="built_in">s2</span>, ..., <span class="meta">sn</span>]</span><br></pre></td></tr></table></figure>
<p>样本中的每个值都是真值与误差的和。</p>
<figure class="highlight armasm"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">算数平均值：</span><br><span class="line">m = (<span class="built_in">s1</span> + <span class="built_in">s2</span> + ... + <span class="meta">sn</span>) / n</span><br></pre></td></tr></table></figure>
<p>算数平均值表示对真值的无偏估计。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">np.mean(array)</span><br></pre></td></tr></table></figure>
<p>案例：计算收盘价的算术平均值。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">closing_prices = np.loadtxt(</span><br><span class="line">    <span class="string">'../../data/aapl.csv'</span>, delimiter=<span class="string">','</span>,</span><br><span class="line">    usecols=(<span class="number">6</span>), unpack=<span class="literal">True</span>)</span><br><span class="line">mean = <span class="number">0</span></span><br><span class="line"><span class="keyword">for</span> closing_price <span class="keyword">in</span> closing_prices:</span><br><span class="line">    mean += closing_price</span><br><span class="line">mean /= closing_prices.size</span><br><span class="line">print(mean)</span><br><span class="line">mean = np.mean(closing_prices)</span><br><span class="line">print(mean)</span><br></pre></td></tr></table></figure>
<h4 id="加权平均值"><a href="#加权平均值" class="headerlink" title="加权平均值"></a>加权平均值</h4><p>样本：S = [s<sub>1</sub>, s<sub>2</sub>, …, s<sub>n</sub>]</p>
<p>权重：W = [w<sub>1</sub>, w<sub>2</sub>, …, w<sub>n</sub>]</p>
<p>加权平均值：a = (s<sub>1</sub>w<sub>1</sub>+s<sub>2</sub>w<sub>2</sub>+…+s<sub>n</sub>w<sub>n</sub>)/(w<sub>1</sub>+w<sub>2</sub>+…+w<sub>n</sub>)</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">np.average(closing_prices, weights=volumes)</span><br></pre></td></tr></table></figure>
<p>VWAP - 成交量加权平均价格（成交量体现了市场对当前交易价格的认可度，成交量加权平均价格将会更接近这支股票的真实价值）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">closing_prices, volumes = np.loadtxt(</span><br><span class="line">    <span class="string">'../../data/aapl.csv'</span>, delimiter=<span class="string">','</span>,</span><br><span class="line">    usecols=(<span class="number">6</span>, <span class="number">7</span>), unpack=<span class="literal">True</span>)</span><br><span class="line">vwap, wsum = <span class="number">0</span>, <span class="number">0</span></span><br><span class="line"><span class="keyword">for</span> closing_price, volume <span class="keyword">in</span> zip(</span><br><span class="line">        closing_prices, volumes):</span><br><span class="line">    vwap += closing_price * volume</span><br><span class="line">    wsum += volume</span><br><span class="line">vwap /= wsum</span><br><span class="line">print(vwap)</span><br><span class="line">vwap = np.average(closing_prices, weights=volumes)</span><br><span class="line">print(vwap)</span><br></pre></td></tr></table></figure>
<p>TWAP - 时间加权平均价格（时间越晚权重越高，参考意义越大）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> datetime <span class="keyword">as</span> dt</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">dmy2days</span><span class="params">(dmy)</span>:</span></span><br><span class="line">    dmy = str(dmy, encoding=<span class="string">'utf-8'</span>)</span><br><span class="line">    date = dt.datetime.strptime(dmy, <span class="string">'%d-%m-%Y'</span>).date()</span><br><span class="line">    days = (date - dt.date.min).days</span><br><span class="line">    <span class="keyword">return</span> days</span><br><span class="line"></span><br><span class="line">days, closing_prices = np.loadtxt(</span><br><span class="line">    <span class="string">'../../data/aapl.csv'</span>, delimiter=<span class="string">','</span>,</span><br><span class="line">    usecols=(<span class="number">1</span>, <span class="number">6</span>), unpack=<span class="literal">True</span>,</span><br><span class="line">    converters=&#123;<span class="number">1</span>: dmy2days&#125;)</span><br><span class="line">twap = np.average(closing_prices, weights=days)</span><br><span class="line">print(twap)</span><br></pre></td></tr></table></figure>
<h4 id="最值"><a href="#最值" class="headerlink" title="最值"></a>最值</h4><p><strong>np.max()  np.min() np.ptp()：</strong> 返回一个数组中最大值/最小值/极差</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="comment"># 产生9个介于[10, 100)区间的随机数</span></span><br><span class="line">a = np.random.randint(<span class="number">10</span>, <span class="number">100</span>, <span class="number">9</span>)</span><br><span class="line">print(a)</span><br><span class="line">print(np.max(a), np.min(a), np.ptp(a))</span><br></pre></td></tr></table></figure>
<p><strong>np.argmax() mp.argmin()：</strong> 返回一个数组中最大/最小元素的下标</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">print(np.argmax(a), np.argmin(a))</span><br></pre></td></tr></table></figure>
<p><strong>np.maximum() np.minimum()：</strong> 将两个同维数组中对应元素中最大/最小元素构成一个新的数组</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">print(np.maximum(a, b), np.minimum(a, b), sep=<span class="string">'\n'</span>)</span><br></pre></td></tr></table></figure>
<p>案例：评估AAPL股票的波动性。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">highest_prices, lowest_prices = np.loadtxt(</span><br><span class="line">    <span class="string">'../../data/aapl.csv'</span>, delimiter=<span class="string">','</span>,</span><br><span class="line">    usecols=(<span class="number">4</span>, <span class="number">5</span>), dtype=<span class="string">'f8, f8'</span>, unpack=<span class="literal">True</span>)</span><br><span class="line">max_price = np.max(highest_prices)</span><br><span class="line">min_price = np.min(lowest_prices)</span><br><span class="line">print(min_price, <span class="string">'~'</span>, max_price)</span><br></pre></td></tr></table></figure>
<p>查看AAPL股票最大最小值的日期，分析为什么这一天出现最大最小值。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">dates, highest_prices, lowest_prices = np.loadtxt(</span><br><span class="line">    <span class="string">'../../data/aapl.csv'</span>, delimiter=<span class="string">','</span>,</span><br><span class="line">    usecols=(<span class="number">1</span>, <span class="number">4</span>, <span class="number">5</span>), dtype=<span class="string">'U10, f8, f8'</span>,</span><br><span class="line">    unpack=<span class="literal">True</span>)</span><br><span class="line">max_index = np.argmax(highest_prices)</span><br><span class="line">min_index = np.argmin(lowest_prices)</span><br><span class="line">print(dates[min_index], dates[max_index])</span><br></pre></td></tr></table></figure>
<p>观察最高价与最低价的<strong>波动范围</strong>，分析这支股票底部是否坚挺。  </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">dates, highest_prices, lowest_prices = np.loadtxt(</span><br><span class="line">    <span class="string">'../../data/aapl.csv'</span>, delimiter=<span class="string">','</span>,</span><br><span class="line">    usecols=(<span class="number">1</span>, <span class="number">4</span>, <span class="number">5</span>), dtype=<span class="string">'U10, f8, f8'</span>,</span><br><span class="line">    unpack=<span class="literal">True</span>)</span><br><span class="line">highest_ptp = np.ptp(highest_prices)</span><br><span class="line">lowest_ptp = np.ptp(lowest_prices)</span><br><span class="line">print(lowest_ptp, highest_ptp)</span><br></pre></td></tr></table></figure>
<h4 id="中位数"><a href="#中位数" class="headerlink" title="中位数"></a>中位数</h4><p>将多个样本按照大小排序，取中间位置的元素。</p>
<p><strong>若样本数量为奇数，中位数为最中间的元素</strong></p>
<p>1 2000 3000 4000 10000000</p>
<p><strong>若样本数量为偶数，中位数为最中间的两个元素的平均值</strong></p>
<p>1 2000 3000 4000 5000 10000000</p>
<p>案例：分析中位数的算法，测试numpy提供的中位数API：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">closing_prices = np.loadtxt( <span class="string">'../../data/aapl.csv'</span>, </span><br><span class="line">	delimiter=<span class="string">','</span>, usecols=(<span class="number">6</span>), unpack=<span class="literal">True</span>)</span><br><span class="line">size = closing_prices.size</span><br><span class="line">sorted_prices = np.msort(closing_prices)</span><br><span class="line">median = (sorted_prices[int((size - <span class="number">1</span>) / <span class="number">2</span>)] + sorted_prices[int(size / <span class="number">2</span>)]) / <span class="number">2</span></span><br><span class="line">print(median)</span><br><span class="line">median = np.median(closing_prices)</span><br><span class="line">print(median)</span><br></pre></td></tr></table></figure>
<h4 id="标准差"><a href="#标准差" class="headerlink" title="标准差"></a>标准差</h4><p>样本：S = [s1, s2, …, sn]<br>平均值：m = (s1+s2+…+sn)/n<br>离差：D = [d1, d2, …, dn], di = si-m<br>离差方：Q = [q1, q2, …, qn], qi = di<sup>2</sup><br>总体方差：v = (q1+q2+…+qn)/n<br>总体标准差：s = sqrt(v)，方均根<br>样本方差：v’ = (q1+q2+…+qn)/(n-1)<br>样本标准差：s’ = sqrt(v’)，方均根</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line">closing_prices = np.loadtxt(</span><br><span class="line">    <span class="string">'../../data/aapl.csv'</span>, delimiter=<span class="string">','</span>, usecols=(<span class="number">6</span>), unpack=<span class="literal">True</span>)</span><br><span class="line">mean = np.mean(closing_prices)         <span class="comment"># 算数平均值</span></span><br><span class="line">devs = closing_prices - mean           <span class="comment"># 离差</span></span><br><span class="line">dsqs = devs ** <span class="number">2</span>                       <span class="comment"># 离差方</span></span><br><span class="line">pvar = np.sum(dsqs) / dsqs.size        <span class="comment"># 总体方差</span></span><br><span class="line">pstd = np.sqrt(pvar)                   <span class="comment"># 总体标准差</span></span><br><span class="line">svar = np.sum(dsqs) / (dsqs.size - <span class="number">1</span>)  <span class="comment"># 样本方差</span></span><br><span class="line">sstd = np.sqrt(svar)                   <span class="comment"># 样本标准差</span></span><br><span class="line">print(pstd, sstd)</span><br><span class="line">pstd = np.std(closing_prices)          <span class="comment"># 总体标准差</span></span><br><span class="line">sstd = np.std(closing_prices, ddof=<span class="number">1</span>)  <span class="comment"># 样本标准差</span></span><br><span class="line">print(pstd, sstd)</span><br></pre></td></tr></table></figure>
<h4 id="时间数据处理"><a href="#时间数据处理" class="headerlink" title="时间数据处理"></a>时间数据处理</h4><p>案例：统计每个周一、周二、…、周五的收盘价的平均值，并放入一个数组。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> datetime <span class="keyword">as</span> dt</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"></span><br><span class="line"><span class="comment"># 转换器函数：将日-月-年格式的日期字符串转换为星期</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">dmy2wday</span><span class="params">(dmy)</span>:</span></span><br><span class="line">    dmy = str(dmy, encoding=<span class="string">'utf-8'</span>)</span><br><span class="line">    date = dt.datetime.strptime(dmy, <span class="string">'%d-%m-%Y'</span>).date()</span><br><span class="line">    wday = date.weekday()  <span class="comment"># 用 周日</span></span><br><span class="line">    <span class="keyword">return</span> wday</span><br><span class="line"></span><br><span class="line">wdays, closing_prices = np.loadtxt(<span class="string">'../data/aapl.csv'</span>, delimiter=<span class="string">','</span>,</span><br><span class="line">    	usecols=(<span class="number">1</span>, <span class="number">6</span>), unpack=<span class="literal">True</span>, converters=&#123;<span class="number">1</span>: dmy2wday&#125;)</span><br><span class="line"></span><br><span class="line">ave_closing_prices = np.zeros(<span class="number">5</span>)</span><br><span class="line"><span class="keyword">for</span> wday <span class="keyword">in</span> range(ave_closing_prices.size):</span><br><span class="line">    ave_closing_prices[wday] = closing_prices[wdays == wday].mean()</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> wday, ave_closing_price <span class="keyword">in</span> zip(</span><br><span class="line">    	[<span class="string">'MON'</span>, <span class="string">'TUE'</span>, <span class="string">'WED'</span>, <span class="string">'THU'</span>, <span class="string">'FRI'</span>],</span><br><span class="line">        ave_closing_prices):</span><br><span class="line">    print(wday, np.round(ave_closing_price, <span class="number">2</span>))</span><br></pre></td></tr></table></figure>
<h4 id="数组的轴向汇总"><a href="#数组的轴向汇总" class="headerlink" title="数组的轴向汇总"></a>数组的轴向汇总</h4><p>案例：汇总每周的最高价，最低价，开盘价，收盘价。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">func</span><span class="params">(data)</span>:</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"><span class="comment">#func 	处理函数</span></span><br><span class="line"><span class="comment">#axis 	轴向 [0,1]</span></span><br><span class="line"><span class="comment">#array 	数组</span></span><br><span class="line">np.apply_along_axis(func, axis, array)</span><br></pre></td></tr></table></figure>
<p>沿着数组中所指定的轴向，调用处理函数，并将每次调用的返回值重新组织成数组返回。</p>
<h4 id="移动均线"><a href="#移动均线" class="headerlink" title="移动均线"></a>移动均线</h4><p>收盘价5日均线：从第五天开始，每天计算最近五天的收盘价的平均值所构成的一条线。</p>
<p>移动均线算法：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">(a+b+c+d+e)/<span class="number">5</span></span><br><span class="line">(b+c+d+e+f)/<span class="number">5</span></span><br><span class="line">(c+d+e+f+g)/<span class="number">5</span></span><br><span class="line">...</span><br><span class="line">(f+g+h+i+j)/<span class="number">5</span></span><br></pre></td></tr></table></figure>
<p>在K线图中绘制5日均线图</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> datetime <span class="keyword">as</span> dt</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> mp</span><br><span class="line"><span class="keyword">import</span> matplotlib.dates <span class="keyword">as</span> md</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">dmy2ymd</span><span class="params">(dmy)</span>:</span></span><br><span class="line">    dmy = str(dmy, encoding=<span class="string">'utf-8'</span>)</span><br><span class="line">    date = dt.datetime.strptime(dmy, <span class="string">'%d-%m-%Y'</span>).date()</span><br><span class="line">    ymd = date.strftime(<span class="string">'%Y-%m-%d'</span>)</span><br><span class="line">    <span class="keyword">return</span> ymd</span><br><span class="line"></span><br><span class="line">dates, closing_prices = np.loadtxt(<span class="string">'../data/aapl.csv'</span>, delimiter=<span class="string">','</span>,</span><br><span class="line">    usecols=(<span class="number">1</span>, <span class="number">6</span>), unpack=<span class="literal">True</span>, dtype=<span class="string">'M8[D], f8'</span>, converters=&#123;<span class="number">1</span>: dmy2ymd&#125;)</span><br><span class="line">sma51 = np.zeros(closing_prices.size - <span class="number">4</span>)</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(sma51.size):</span><br><span class="line">    sma51[i] = closing_prices[i:i + <span class="number">5</span>].mean()</span><br><span class="line"><span class="comment"># 开始绘制5日均线</span></span><br><span class="line">mp.figure(<span class="string">'Simple Moving Average'</span>, facecolor=<span class="string">'lightgray'</span>)</span><br><span class="line">mp.title(<span class="string">'Simple Moving Average'</span>, fontsize=<span class="number">20</span>)</span><br><span class="line">mp.xlabel(<span class="string">'Date'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">mp.ylabel(<span class="string">'Price'</span>, fontsize=<span class="number">14</span>)</span><br><span class="line">ax = mp.gca()</span><br><span class="line"><span class="comment"># 设置水平坐标每个星期一为主刻度</span></span><br><span class="line">ax.xaxis.set_major_locator(md.WeekdayLocator( byweekday=md.MO))</span><br><span class="line"><span class="comment"># 设置水平坐标每一天为次刻度</span></span><br><span class="line">ax.xaxis.set_minor_locator(md.DayLocator())</span><br><span class="line"><span class="comment"># 设置水平坐标主刻度标签格式</span></span><br><span class="line">ax.xaxis.set_major_formatter(md.DateFormatter(<span class="string">'%d %b %Y'</span>))</span><br><span class="line">mp.tick_params(labelsize=<span class="number">10</span>)</span><br><span class="line">mp.grid(linestyle=<span class="string">':'</span>)</span><br><span class="line">dates = dates.astype(md.datetime.datetime)</span><br><span class="line">mp.plot(dates, closing_prices, c=<span class="string">'lightgray'</span>, label=<span class="string">'Closing Price'</span>)</span><br><span class="line">mp.plot(dates[<span class="number">4</span>:], sma51, c=<span class="string">'orangered'</span>, label=<span class="string">'SMA-5(1)'</span>)</span><br><span class="line">mp.legend()</span><br><span class="line">mp.gcf().autofmt_xdate()</span><br><span class="line">mp.show()</span><br></pre></td></tr></table></figure>
<h4 id="卷积"><a href="#卷积" class="headerlink" title="卷积"></a>卷积</h4><p>激励函数：g(t)</p>
<p>单位激励下的响应函数：f(t)</p>
<p>绘制时间（t）与痛感（h）的函数关系图。</p>
<p>a = [1 2 3 4 5]    （理解为某单位时间的击打力度序列）</p>
<p>b = [6 7 8]        （理解为痛感系数序列）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">c = numpy.convolve(a, b, 卷积类型)</span><br><span class="line"></span><br><span class="line">                <span class="number">40</span>  <span class="number">61</span>  <span class="number">82</span>         - 有效卷积(valid)</span><br><span class="line">            <span class="number">19</span>  <span class="number">40</span>  <span class="number">61</span>  <span class="number">82</span>  <span class="number">67</span>     - 同维卷积(same)</span><br><span class="line">        <span class="number">6</span>   <span class="number">19</span>  <span class="number">40</span>  <span class="number">61</span>  <span class="number">82</span>  <span class="number">67</span>  <span class="number">40</span> - 完全卷积(full)</span><br><span class="line"><span class="number">0</span>   <span class="number">0</span>   <span class="number">1</span>   <span class="number">2</span>   <span class="number">3</span>   <span class="number">4</span>   <span class="number">5</span>   <span class="number">0</span>   <span class="number">0</span></span><br><span class="line"><span class="number">8</span>   <span class="number">7</span>   <span class="number">6</span></span><br><span class="line">    <span class="number">8</span>   <span class="number">7</span>   <span class="number">6</span></span><br><span class="line">        <span class="number">8</span>   <span class="number">7</span>   <span class="number">6</span></span><br><span class="line">            <span class="number">8</span>   <span class="number">7</span>   <span class="number">6</span></span><br><span class="line">                <span class="number">8</span>   <span class="number">7</span>   <span class="number">6</span></span><br><span class="line">                    <span class="number">8</span>   <span class="number">7</span>   <span class="number">6</span></span><br><span class="line">                        <span class="number">8</span>    <span class="number">7</span>   <span class="number">6</span></span><br></pre></td></tr></table></figure>
<p><strong>5日移动均线序列可以直接使用卷积实现</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">a = [a, b, c, d, e, f, g, h, i, j] </span><br><span class="line">b = [<span class="number">1</span>/<span class="number">5</span>, <span class="number">1</span>/<span class="number">5</span>, <span class="number">1</span>/<span class="number">5</span>, <span class="number">1</span>/<span class="number">5</span>, <span class="number">1</span>/<span class="number">5</span>]</span><br></pre></td></tr></table></figure>
<p><strong>使用卷积函数numpy.convolve(a, b, 卷积类型)实现5日均线</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">sma52 = np.convolve( closing_prices, np.ones(<span class="number">5</span>) / <span class="number">5</span>, <span class="string">'valid'</span>)</span><br><span class="line">mp.plot(dates[<span class="number">4</span>:], sma52, c=<span class="string">'limegreen'</span>, alpha=<span class="number">0.5</span>,</span><br><span class="line">        linewidth=<span class="number">6</span>, label=<span class="string">'SMA-5(2)'</span>)</span><br></pre></td></tr></table></figure>
<p><strong>使用卷积函数numpy.convolve(a, b, 卷积类型)实现10日均线</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">sma10 = np.convolve(closing_prices, np.ones(<span class="number">10</span>) / <span class="number">10</span>, <span class="string">'valid'</span>)</span><br><span class="line">mp.plot(dates[<span class="number">9</span>:], sma10, c=<span class="string">'dodgerblue'</span>, label=<span class="string">'SMA-10'</span>)</span><br></pre></td></tr></table></figure>
<p><strong>使用卷积函数numpy.convolve(a, b, 卷积类型)实现加权5日均线</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">weights = np.exp(np.linspace(<span class="number">-1</span>, <span class="number">0</span>, <span class="number">5</span>))</span><br><span class="line">weights /= weights.sum()</span><br><span class="line">ema5 = np.convolve(closing_prices, weights[::<span class="number">-1</span>], <span class="string">'valid'</span>)</span><br><span class="line">mp.plot(dates[<span class="number">4</span>:], sma52, c=<span class="string">'limegreen'</span>, alpha=<span class="number">0.5</span>,</span><br><span class="line">        linewidth=<span class="number">6</span>, label=<span class="string">'SMA-5'</span>)</span><br></pre></td></tr></table></figure>
<h4 id="布林带"><a href="#布林带" class="headerlink" title="布林带"></a>布林带</h4><p>布林带由三条线组成：</p>
<p>中轨：移动平均线</p>
<p>上轨：中轨+2x5日收盘价标准差    （顶部的压力）</p>
<p>下轨：中轨-2x5日收盘价标准差     （底部的支撑力）</p>
<p>布林带收窄代表稳定的趋势，布林带张开代表有较大的波动空间的趋势。</p>
<p><strong>绘制5日均线的布林带</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">weights = np.exp(np.linspace(<span class="number">-1</span>, <span class="number">0</span>, <span class="number">5</span>))</span><br><span class="line">weights /= weights.sum()</span><br><span class="line">em5 = np.convolve(closing_prices, weights[::<span class="number">-1</span>], <span class="string">'valid'</span>)</span><br><span class="line">stds = np.zeros(em5.size)</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(stds.size):</span><br><span class="line">    stds[i] = closing_prices[i:i + <span class="number">5</span>].std()</span><br><span class="line">stds *= <span class="number">2</span></span><br><span class="line">lowers = medios - stds</span><br><span class="line">uppers = medios + stds</span><br><span class="line"></span><br><span class="line">mp.plot(dates, closing_prices, c=<span class="string">'lightgray'</span>, label=<span class="string">'Closing Price'</span>)</span><br><span class="line">mp.plot(dates[<span class="number">4</span>:], medios, c=<span class="string">'dodgerblue'</span>, label=<span class="string">'Medio'</span>)</span><br><span class="line">mp.plot(dates[<span class="number">4</span>:], lowers, c=<span class="string">'limegreen'</span>, label=<span class="string">'Lower'</span>)</span><br><span class="line">mp.plot(dates[<span class="number">4</span>:], uppers, c=<span class="string">'orangered'</span>, label=<span class="string">'Upper'</span>)</span><br></pre></td></tr></table></figure>
      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
            <a href="/tags/数据分析/" rel="tag"># 数据分析</a>
          
            <a href="/tags/AI进阶/" rel="tag"># AI进阶</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/11/29/datascience/数据分析-概述/" rel="next" title="数据分析-概述">
                <i class="fa fa-chevron-left"></i> 数据分析-概述
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/12/03/datascience/Matplotlib/" rel="prev" title="Matplotlib">
                Matplotlib <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.JPG" alt="任成">
            
              <p class="site-author-name" itemprop="name">任成</p>
              <div class="site-description motion-element" itemprop="description"></div>
          </div>

          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0NvZGVyQ3VydmU=" title="GitHub &rarr; https://github.com/CoderCurve"><i class="fa fa-fw fa-github"></i>GitHub</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="bWFpbHRvOnJlbmNoZW5nMTFAaWNsb3VkLmNvbQ==" title="E-Mail &rarr; mailto:rencheng11@icloud.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</span>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#numpy概述"><span class="nav-number">1.</span> <span class="nav-text">numpy概述</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#numpy历史"><span class="nav-number">1.1.</span> <span class="nav-text">numpy历史</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#numpy的核心：多维数组"><span class="nav-number">1.2.</span> <span class="nav-text">numpy的核心：多维数组</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#numpy基础"><span class="nav-number">2.</span> <span class="nav-text">numpy基础</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#ndarray数组"><span class="nav-number">2.1.</span> <span class="nav-text">ndarray数组</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#内存中的ndarray对象"><span class="nav-number">2.1.1.</span> <span class="nav-text">内存中的ndarray对象</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#ndarray数组对象的特点"><span class="nav-number">2.1.2.</span> <span class="nav-text">ndarray数组对象的特点</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#ndarray数组对象的创建"><span class="nav-number">2.1.3.</span> <span class="nav-text">ndarray数组对象的创建</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#ndarray对象属性的基本操作"><span class="nav-number">2.1.4.</span> <span class="nav-text">ndarray对象属性的基本操作</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#ndarray对象属性操作详解"><span class="nav-number">2.1.5.</span> <span class="nav-text">ndarray对象属性操作详解</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#ndarray数组对象的维度操作"><span class="nav-number">2.1.5.1.</span> <span class="nav-text">ndarray数组对象的维度操作</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#ndarray数组切片操作"><span class="nav-number">2.1.5.2.</span> <span class="nav-text">ndarray数组切片操作</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#ndarray数组的掩码操作"><span class="nav-number">2.1.5.3.</span> <span class="nav-text">ndarray数组的掩码操作</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#多维数组的组合与拆分"><span class="nav-number">2.1.5.4.</span> <span class="nav-text">多维数组的组合与拆分</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#ndarray类的其他属性"><span class="nav-number">2.1.6.</span> <span class="nav-text">ndarray类的其他属性</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#相关函数"><span class="nav-number">2.2.</span> <span class="nav-text">相关函数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#算数平均值"><span class="nav-number">2.2.1.</span> <span class="nav-text">算数平均值</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#加权平均值"><span class="nav-number">2.2.2.</span> <span class="nav-text">加权平均值</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#最值"><span class="nav-number">2.2.3.</span> <span class="nav-text">最值</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#中位数"><span class="nav-number">2.2.4.</span> <span class="nav-text">中位数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#标准差"><span class="nav-number">2.2.5.</span> <span class="nav-text">标准差</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#时间数据处理"><span class="nav-number">2.2.6.</span> <span class="nav-text">时间数据处理</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#数组的轴向汇总"><span class="nav-number">2.2.7.</span> <span class="nav-text">数组的轴向汇总</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#移动均线"><span class="nav-number">2.2.8.</span> <span class="nav-text">移动均线</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#卷积"><span class="nav-number">2.2.9.</span> <span class="nav-text">卷积</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#布林带"><span class="nav-number">2.2.10.</span> <span class="nav-text">布林带</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">  <span class="exturl" data-url="aHR0cDovL3d3dy5iZWlhbi5taWl0Lmdvdi5jbg==">京ICP备18001214号 </span>&copy; 2014 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">任成</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
    <span title="站点总字数">277k</span>
  

  
</div>









        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/utils.js?v=7.1.2"></script>

  <script src="/js/motion.js?v=7.1.2"></script>



  
  


  <script src="/js/affix.js?v=7.1.2"></script>

  <script src="/js/schemes/pisces.js?v=7.1.2"></script>



  
  <script src="/js/scrollspy.js?v=7.1.2"></script>
<script src="/js/post-details.js?v=7.1.2"></script>



  


  <script src="/js/next-boot.js?v=7.1.2"></script>


  

  
  <script src="/js/exturl.js?v=7.1.2"></script>


  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
  

  
  

  


  

  
<script>
if ($('body').find('pre.mermaid').length) {
  $.ajax({
    type: 'GET',
    url: '//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js',
    dataType: 'script',
    cache: true,
    success: function() {
      mermaid.initialize({
        theme: 'forest',
        logLevel: 3,
        flowchart: { curve: 'linear' },
        gantt: { axisFormat: '%m/%d/%Y' },
        sequence: { actorMargin: 50 }
      });
    }
  });
}
</script>


  

  

  

  

  

  

  

  

  

</body>
</html>
